package com.heima.app.gateway.filter;

import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 是否为登录请求
        ServerHttpRequest request = exchange.getRequest();
        if (request.getURI().toString().contains("/login")) {
            // 直接放行
            return chain.filter(exchange);
        }
        // 获取token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.hasLength(token)) {
            // 有token
            try {
                int code = AppJwtUtil.verifyToken(AppJwtUtil.getClaimsBody(token));
                if (code == 0 || code == -1) {
                    // 校验成功，直接放行
                    log.info("jwt校验成功，已放行");
                    return chain.filter(exchange);
                } else {
                    // 返回没有权限访问
                    ServerHttpResponse response = exchange.getResponse();
                    // 设置状态码为401，表示未授权
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    log.error("jwt校验失败");
                    return response.setComplete();
                }
            } catch (Exception e) {
                ServerHttpResponse response = exchange.getResponse();
                // 设置状态码为401，表示未授权
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                log.error("jwt校验失败");
                return response.setComplete();
            }

        } else {
            // 没有token，返回没有权限访问
            ServerHttpResponse response = exchange.getResponse();
            // 设置状态码为401，表示未授权
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            log.error("jwt校验失败");
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        // 决定过滤器的顺序，数字越小优先级越高
        return -1;
    }
}
